$(document).ready(function(){
	
	generateField("#playerField", false);
	generateInfoField("#playerField");
	generateField("#enemyField", true);
	
	
	$("#chatInput").keypress(function(event){
		if(event.which==13){ // event 13 is pressing enter
			$("#scroll").html(this.value + "<br />" + $("#scroll").html());
			this.value="";
		}
	});
	$("#mainbutton").click(mainButtonClick);
	$("#playerField .field .kuubik").mouseenter(mouseEnterPlaceShip).mouseleave(mouseLeavePlaceShip);
	$("#selectedGameField").val("");
	poll();
});

/////////////////////////////////////////////////
//// UI RELATED SHIZZ
/////////////////////////////////////////////////
function poll(){
	setInterval(function(){
		$.ajax({ url: "lobby/", success: loadGameListFromData, dataType: "json",  timeout: 10000 });
	},3000);
};


function loadGameListFromData(data){
	var elem = $("#gamesList");
	var newIds = [];
	$.each(data,function(key,val){
		var existing = elem.children("#"+val.id);
		if(existing.length==0){
			elem.append("<div id='" + val.id + "' class='gameListItem' onclick='selectGame(this);'>" + val.name + "</div>");
		}
		newIds.push(val.id);
	});
	elem.children().each(function(){
		var selected = $("#selectedGameField");
		if(jQuery.inArray(this.id,newIds) < 0){
			if(selected.val()==this.id){
				selected.val("");
			}
			$(this).remove();
		}
	});
}

function selectGame(sel){
	$(".gameListItem").each(function (){$(this).attr("class","gameListItem");});
	$(sel).attr("class","gameListItem selected");
	$("#selectedGameField").val(sel.id);
}

function joinGame(){
	var selectedGame = $("#selectedGameField").val();
	if(selectedGame==""){
		alert("Vali mäng!");
		return;
	}
	var userName = $("#playerName").val();
	if(checkUserName(userName)) {
		return;
	}
	
	sendData("lobby/",'{"userName":"'+userName+'","gameId":"'+selectedGame+'"}', parseJoinGameSuccess);
}

function parseJoinGameSuccess(data){
	if(data.outcome=="failure"){
		alert("failed");
		return;
	}
	toggleLobby();
}

function createGame(){
	var userName = $("#playerName").val();
	if(checkUserName(userName)) {
		return;
	}
	sendData("lobby/",'{"userName":"'+userName+'","gameId":""}', parseCreateGameSuccess);
}

function parseCreateGameSuccess(data){
	if(data.outcome=="failure"){
		alert("failed");
		return;
	}
	toggleLobby();
}

function sendData(path, myData, successFunction) {
    jQuery.ajax({
        url:path,
        data:{"data":myData},
        success:successFunction || function (data) {
            if (data.status == "FAILURE") {
                alert("ERROR: " + data.reason);
            }
        },
        type:"post",
        timeout:30000
    });
}

function toggleLobby(){
	$("#lobby").toggle();
	$("#game").toggle();
	$("#foot").toggle();
}

function checkUserName(userName){
	if(userName=="") {
		alert("Sisesta mängija nimi");
		return true;
	}
	return false;
}

var shipFilesBySize = ["","graphics/yhene.gif","graphics/patrol.gif","graphics/battleship.gif","graphics/carrier.gif"];
var selectedPlacement="";
var placedShips = [];
var shipCountBySize = [0,4,3,2,1];
var LETTERS = "ABCDEFGHIJKLMNOPQRST";//that is more than we need


function mouseEnterPlaceShip(){
	if(isValidCoordinate($(this).attr("id").substring(6))){
		$(this).css("background-color","blue").click(placeShip);
	}
}

function mouseLeavePlaceShip(){
	if($(this).attr("id")!=selectedPlacement){
		$(this).attr("style","");
	}
	$(this).unbind("click");
}

function placeShip(){
	if(selectedPlacement==""){
		selectedPlacement=$(this).attr("id");
		$(this).css("background-color","blue");
	} else {
		var laev = new Ship(selectedPlacement.substring(6),$(this).attr("id").substring(6));
		if(laev.isValidSize() && countPlacedShipsBySize(laev.size)<shipCountBySize[laev.size]){
			placedShips.push(laev);
			drawShip(laev,"player");
		} else {
			alert("sellise suurusega laeva ei tohi paigutada!");
		}
		$("#" + selectedPlacement).attr("style","");
		selectedPlacement="";
	}
}

function loadBoxAndFadeIn(contentType){
	$("#info-box-head").load("info/" + contentType + "/head");
	$("#info-box-body").load("info/" + contentType + "/body");
    $('#overlay').fadeIn('fast',function(){
        $('#box').animate({'top':'160px'},500);
    });
}
function boxFadeOut(){
    $('#box').animate({'top':'-300px'},500,function(){
        $('#overlay').fadeOut('fast');
    });
    $("#info-box-head").text("");
    $("#info-box-body").text("");
}

function isValidCoordinate(coord){
	for(var i=0;i<placedShips.length;i++){
		if(placedShips[i].isCollision(coord)){
			return false;
		}
	}
	return true;
}

function drawShip(laev,idPrefix){
	var vertical = laev.orientation==0;
	var divId=idPrefix+laev.smallerCoordinate;
	var laevaPilt=shipFilesBySize[laev.size];
	if(vertical && laev.size!=1){
		laevaPilt=laevaPilt.replace(".gif","v.gif");
	}
	$("#"+divId).append("<img id=\""+divId+"Ship\" class=\"ship\" src=\""+laevaPilt+"\" alt=\"\" />");
	$("#"+divId+"Ship").click(removeShip);
}

function removeShip(){
	var coordinate = $(this).attr("id").substring(6);
	coordinate=coordinate.substring(0,coordinate.indexOf("Ship"));
	for(var i=0;i<placedShips.length;i++){
		if(placedShips[i].isHit(coordinate)){
			placedShips.splice(i, 1);
			break;
		}
	}
	$(this).remove();
}

function mainButtonClick(){
	toggleOverlay();
	resetEnemyField();
	if(!isAllShipsPlaced()){
		alert("Paigutage kõik laevad!");
		toggleOverlay();
		return;
	}
	$("#playerField .field .kuubik").unbind("mouseenter").unbind("mouseleave");
	$("#enemyField .field .kuubik").unbind("click").click(bombEnemyField);
	$("#infoText").text("TULISTA!");
	$(".ship").unbind("click");
	toggleOverlay();	
}


function generateInfoField(divId){
	$(divId).append(generateDivElementString("infoText","transparentBackground","Paiguta laevad!"));
}

function generateField(divId,enemyField){
	generateFieldHead(divId,enemyField);
	if(enemyField){
		generateShipField(divId,enemyField);
		generateLetterField(divId,enemyField);
	} else {
		generateLetterField(divId,enemyField);
		generateShipField(divId,enemyField);
	}
}

function generateShipField(divId,enemyField){
	$(divId).append(generateDivElementString(false,"field " + (!enemyField?"":"floatLeft"),false));	
	var fiild = $(divId + " .field");
	for(var i=0;i<100;i++){
		var modulus = i%10;
		var number = Math.floor(i/10);
		fiild.append(generateDivElementString((enemyField?"enemy":"player")+LETTERS.substring(number, number+1)+(modulus+1),"kuubik",false));		
	}
}

function generateFieldHead(divId,enemyField){
	$(divId).append(generateDivElementString(false,"fieldHead",false));
	var fieldHead = $(divId + " .fieldHead");
	if(!enemyField){
		fieldHead.append(generateDivElementString(false,"kuubik",false));
	}
	for(var i=1;i<=10;i++){
		fieldHead.append(generateDivElementString(false,"kuubik",i));
	}
	if(enemyField){
		fieldHead.append(generateDivElementString(false,"kuubik",false));
	}
}

function generateLetterField(divId,enemyField){
	$(divId).append(generateDivElementString(false,"fieldLetters " + (enemyField?"":"floatLeft"),false));
	for(var i=0;i<10;i++){
		$(divId + " .fieldLetters").append(generateDivElementString(false,"kuubik",LETTERS.substring(i, i+1)));		
	}
}

function generateDivElementString(id,klass,sisu){
	return "<div" 
	+ (id?" id=\"" + id + "\"":"")
	+ (klass?" class=\"" + klass + "\"":"")
	+ ">"
	+ (sisu?sisu:"")
	+ "</div>"
	;
}

function toggleOverlay(){
	var elem = $("#overlay");
	if(elem.css("display") == "none"){
		elem.css("display","block");
	} else {
		elem.css("display","none");
	}
}



//////////////////////////////////////////////////////////
/// GAME LOGIC RELATED FUNCTIONS
//////////////////////////////////////////////////////////

var playerFieldBombedCoordinates=[];

function countPlacedShipsBySize(size){
	var count=0;
	for(var i=0;i<placedShips.length;i++){
		if(placedShips[i].size==size){
			count++;
		}
	}
	return count;
}
function isAllShipsPlaced(){
	for(var i=1;i<shipCountBySize.length;i++){
		if(shipCountBySize[i]!=countPlacedShipsBySize(i)) return false;
	}
	return true;
}

function bombEnemyField(){
	toggleOverlay();
	$(this).css("opacity","1");
	$(this).css("background-color","transparent");
	$(this).unbind("click");
	if(isHit($(this).attr("id"))){
		$(this).css("background-color","red");
		toggleOverlay();
		return;

	}
	waitForEnemyBomb(); // this is one of the most stupid things you could do in a war!
	toggleOverlay();
}

function isHit(id){
	var gotHit=false;
	for(var i=0;i<placedShips.length;i++){
		if(placedShips[i].isHit(id.substring(5))){
			gotHit=true;
			if(placedShips[i].bomb(id.substring(5))){
				drawShip(placedShips[i],"enemy");
			}
		}
	}
	return gotHit;
}

function waitForEnemyBomb(){
	while(playerFieldBombedCoordinates.length<100){
		var randomCoordinate=LETTERS.charAt(Math.floor(Math.random()*10))+(Math.floor(Math.random()*10)+1);
		if(jQuery.inArray(randomCoordinate,playerFieldBombedCoordinates)<0){
			playerFieldBombedCoordinates.push(randomCoordinate);
			$("#player"+randomCoordinate).css("background-color","red");
			
			break;
		}
		
	}	
}

//////////////////////
// TEMPORARY SHIZZ
//////////////////////

function resetEnemyField(){
	$("#enemyField .field .kuubik").attr("style","");
}
